/*
 * Copyright (c) 2006, 2022, webrx.cn All rights reserved.
 *
 */
package com.desire.interceptor;


import com.desire.snowflake.IdWorker;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.springframework.beans.factory.annotation.Autowired;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * <p>Project: mybatis2022 - SnowFlakeInterceptor
 * <p>Powered by webrx On 2022-04-12 14:45:11
 * <p>Created by IntelliJ IDEA
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 17
 */

@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})})
public class SnowFlakeInterceptor implements Interceptor {
    @Autowired
    private IdWorker idw;

    @Override
    public Object intercept(Invocation io) throws Throwable {
        MappedStatement ms = (MappedStatement) io.getArgs()[0];
        if ("INSERT".equals(ms.getSqlCommandType().toString())) {
            //System.out.println("11111111111111111---------------------------------------------------------------------------------------");
            //System.out.println(io.getTarget().getClass().getName()); //org.apache.ibatis.executor.CachingExecutor
            //System.out.println(io.getMethod().getName());//update
            //System.out.println(io.getMethod().getReturnType().getName());//int
            //System.out.println(List.of(io.getArgs())); //[org.apache.ibatis.mapping.MappedStatement@aa10649, {price=28, name=《javascript程序设计入门》}]
            Object obj = io.getArgs()[1];
            if (obj instanceof HashMap) {
                Map<String, Object> map = (Map<String, Object>) obj;
                map.put("id", idw.nextId());
            } else {
                Method m = obj.getClass().getMethod("setId", Long.class);
                m.invoke(obj, idw.nextId());
            }
            return io.proceed();
        }else{
            return io.proceed();
        }

    }

    /**
     * Plugin.wrap生成拦截代理对象
     */
    @Override
    public Object plugin(Object o) {
        if (o instanceof Executor) {
            return Plugin.wrap(o, this);
        } else {
            return o;
        }
    }

    @Override
    public void setProperties(Properties properties) {

    }
}
